﻿function overlay() {
    console.debug("overlay");
    var _doc = $(document);
    var _win = $(window);
    var _docHeight = _doc.height();
    var _winHeight = _win.height();
    var _winWidth = _win.width();
    jQuery('body')
      .append('<div id="sd_overlay" style="display:none;"></div>')
      .find('#sd_overlay')
      .css({
          width: _winWidth,
          height: _winHeight,
          position: 'fixed',
          top: 0,
          left: 0
      }).css('z-index', '2000')
      .attr('class', 'sd_overlay')
      .fadeIn(100);
  };

  function parseJSON(object) {
      var s = "";
      s += '{"name":"' + object.name + '",';
      s += '"object":"' + object.object + '"';
      if (object.children.length > 0) {
          s += ',"children":[';
          for (var i = 0; i < object.children.length; i++) {
              if (i > 0) {
                  s += ',';
              }
              s += parseJSON(object.children[i]);
          }
          s += ']';
      }
      s += '}';
      return s;
  }



  $(document).ready(function () {
      overlay();
      var region = $('<select></select>');
      var locality = $('<select></select>');

      init($(this));

      //TEST
      $('#btnTest').click(function () {
          //          $.getJSON('items', { type: "Doctor" }, function (data) {
          //              var s = parseJSON(data);
          //              console.debug(s);
          //              alert(s);
          //          });

          var jsonObj = $.parseJSON(
                $.ajax(
                    {
                        url: "items?type=Doctor",
                        async: false,
                        dataType: 'json'
                    }
                ).responseText
            );
          var s = parseJSON(jsonObj);
          console.debug(s);
          alert(s);

          return false;
      });
      //END TEST

      $('a[href=#Menu1_SkipLink]').remove();
      var hff = $("#hfFilters");
      if (hff.length > 0) {
          var fs = hff.val().split(';');
          for (var i in fs) {
              var input = fs[i].split('=');
              $('#_filterText' + input[0]).val(input[1]).keyup();
          }
      }
      $(".scroll-container:first").scrollTop($('#hfScroll').val());
      //      if (sc.length > 0) {
      //          console.debug('scroll to ' + $('#hfScroll').val());
      //          sc.css('border', '1px solid red');
      //          sc.scrollTop = $('#hfScroll').val();
      //      }
      $('input[type=submit][id$=btnSave]').live("click", function (event) {
          if (!confirm("Вы хотите сохранить изменения?")) {
              return false;
          } else {
              var message = "";
              var form = $(this).closest('form');
              var fill = true;
              form.find('input[type=text]:not(.nullable):not(.full):not(._filterText):not(#tfAddMember):not(#tfAddQuestion)').each(function () {
                  var value = $(this).val();
                  if (value == '') {
                      if (fill) {
                          message = "Заполните необходимые поля\n";
                          fill = false;
                      }
                      $(this).css('border', '1px solid red');
                  }
              });
              var len = form.find('select:not(.nullable) option:selected[value="null"]').parent().css('border', '1px solid red').length;
              if (len > 0) {
                  message += "Необходимо выбрать значение в выпадающем списке\n";
              }
              if (!checkSpecAndGroup()) {
                  message += "Специальность не соответствует экспертной группе\n";
              }
              if (message.length > 0) {
                  alert(message);
                  return false;
              }
          }
      });


      var reg = $('select[id$=comboRegion] option:selected').val();
      var loc = $('select[id$=comboLocality] option:selected').val();
      //alert(region);
      $('select[id$=comboLocality] option[region][region!=' + reg + ']').each(function () {
          region.append($(this));
      });
      $('select[id$=comboInstitution] option[locality][locality!=' + loc + ']').each(function () {
          locality.append($(this));
      });

      $('select[id$=comboRegion]').live('change', function () {
          console.debug("comboRegion change");
          $('select[id$=comboLocality] option[region]').each(function () {
              region.append($(this));
          });
          var t = $('option:selected', this).val();
          var opt = $('option[region=' + t + ']', region);
          $('select[id$=comboLocality]').append(opt);

          $('select[id$=comboInstitution] option[locality]').each(function () {
              locality.append($(this));
          });
          var t = $('select[id$=comboLocality] option:selected').val();
          var opt = $('option[locality=' + t + ']', locality);
          $('select[id$=comboInstitution]').append(opt);
      });
      $('select[id$=comboLocality]').live('change', function () {
          $('select[id$=comboInstitution] option[locality]').each(function () {
              locality.append($(this));
          });
          var t = $('option:selected', this).val();
          $('#hfLocality').val(t);
          var opt = $('option[locality=' + t + ']', locality);
          $('select[id$=comboInstitution]').append(opt);
      });


      $('table#TableDocInOrder a.up').live('click', function () {
          var tr = $(this).parent().parent();
          $(this).removeClass('up').addClass('down');
          tr.find('td').eq(2).remove();
          $('table#TableDoctors tbody').prepend(tr);
          var values = $('#hfDocInOrder').val();
          var id = $(this).attr('id');
          console.debug('id: ' + id + " values: " + values);
          values = values.replace(',' + id, '');
          console.debug(" values: " + values);
          $('#hfDocInOrder').val(values);
      });

      $('table#TableDoctors a.down').live('click', function () {
          var tr = $(this).parent().parent();
          $(this).removeClass('down').addClass('up');
          tr.find('td').eq(1).after('<td />')
          $('table#TableDocInOrder tbody').prepend(tr);
          var values = $('#hfDocInOrder').val();
          var id = $(this).attr('id');
          console.debug('id: ' + id + " values: " + values);
          values = values + ',' + id;
          console.debug(" values: " + values);
          $('#hfDocInOrder').val(values);
          var form = tr.closes('form');
          resizeOrderTables(form);
      });

      $('form a#editOrder:not(.disabled)').live('click', function () {
          $(this).toggleClass('active');
          var form = $(this).closest('form');
          updateOrder(form);
      });

      //        $('select[id$=comboRegion]').live('change', function () {
      //            $('input[id$=btUpdateLocality]').click();
      //        });
      //        $('select[id$=comboLocality]').live('change', function () {
      //            $('input[id$=btUpdateInstitution]').click();
      //        });

      $('a.delete.member').live("click", function () {
          var id = $(this).attr('id');
          var text = $(this).parent().next('td').text();
          var member = ';' + id + '=' + text;
          //alert(member);
          $(this).parent().parent().remove();
          var members = $('input#hfMembers').val();
          members = members.replace(member, '');
          $('input#hfMembers').val(members);
          return false;
      });
      $('a#addMember').live("click", function () {
          var id = '0';
          var text = $('#tfAddMember').val();
          text = text.replace(/;/g, '').replace(/=/g, '');
          if (text > '') {
              var member = ';' + id + '=' + text;
              //alert(member);
              var tr = $('<tr><td width="18px"><a id="' + id + '" class="delete member"></a></td><td>' + text + '</td></tr>');
              $('#tblMembers').append(tr);
              var members = $('input#hfMembers').val();
              members += member;
              $('input#hfMembers').val(members);
          }
          return false;
      });

      $('a.delete.question').live("click", function () {
          var id = $(this).attr('id');
          var text = $(this).parent().next('td').text();
          var member = ';' + id + '=' + text;
          //alert(member);
          $(this).parent().parent().remove();
          var members = $('input#hfQuestions').val();
          members = members.replace(member, '');
          $('input#hfQuestions').val(members);
          return false;
      });
      $('a#addQuestion').live("click", function () {
          var id = '0';
          var text = $('#tfAddQuestion').val();
          text = text.replace(/;/g, '').replace(/=/g, '');
          var member = ';' + id + '=' + text;
          if (text > '') {
              //alert(member);
              var tr = $('<tr><td width="18px"><a id="' + id + '" class="delete question"></a></td><td>' + text + '</td></tr>');
              $('#tblQuestions').append(tr);
              var members = $('input#hfQuestions').val();
              members += member;
              $('input#hfQuestions').val(members);
          }
          return false;
      });
      $('a#addSpecialityToGroup').live("click", function () {
          var opt = $('#comboSpeciality option:selected:not([disabled])');
          if (opt.length > 0) {
              var value = opt.val();
              var title = opt.text();
              var tr = $('<tr><td width="18"><a id="' + value + '" class="delete deleteSpecialityFromGroup"></a></td><td>' + title + '</td></tr>');
              $('#tblSpecialityList').prepend(tr);
              opt.attr('disabled', 'disabled');
              var val = $('#hfSpecialities').val();
              val = val.replace(';' + value, '') + ';' + value;
              $('#hfSpecialities').val(val);
          }
          return false;
      });
      $('a.deleteSpecialityFromGroup').live("click", function () {
          var id = $(this).attr('id');
          $(this).parent().parent().remove();
          $('#comboSpeciality option[value=' + id + ']').removeAttr('disabled');
          var val = $('#hfSpecialities').val().replace(';' + id, '');
          //alert(val);
          $('#hfSpecialities').val(val);
      });

      var fixHelper = function (e, ui) {
          ui.children().each(function () {
              $(this).width($(this).width());
          });
          return ui;
      };
      $("#tblSpeciality tbody").sortable({
          helper: fixHelper,
          stop: function (event, ui) {
              var id = $('a.edit', ui.item).attr('href').replace(/.*id=/, '');
              var pos = ui.item.index();
              $('#hfSpecNumber').val(id + '=' + pos).closest('form').submit();
          },
          handle: $(".updown")
      }).disableSelection();

      var filter = $('#_TableDoctors #_filterText5');
      $('#treeLpu a').click(function () {
          var txt = $(this).text();
          if (txt > '') {
              if ($(this).attr('title').length > 0) {
                  filter.val(txt.trim());
                  $('#treeLpu').dialog('close');
                  filter.keyup();
              }
              return false;
          }
      });
      if (filter.length > 0) {
          var fw = filter.width();
          filter.width((parseInt(fw) - 30) + 'px');
          //filter.css('float', 'right');
          var tree = $('#selectLpuTree');
          tree.css('float', 'right');
          filter.after(tree);
          //          tree.click(function () {
          //              var div = $('#lpuTree');
          //              var w = 500;
          //              var h = 400;

          //              var wh = parseInt($(window).height());

          //              if (h > wh - 100) {
          //                  h = wh - 200;
          //              }
          //              $('#treeLpu').dialog({ modal: true,
          //                  height: h + 100,
          //                  width: w + 20,
          //                  open: function () {
          //                  },
          //                  close: function () {
          //                  }
          //              });
          //              return false;
          //          });
      }

      initFilter('body');

      $('#sd_overlay').remove();
  });

  function resizeOrderTables(form) {
      $('#TableDoctors tr:first td', form).each(function (i) {
          var w = $(this).width();
          $('#_TableDoctors tr:first th').eq(i).css('width', w + 'px');
      });
      $('#TableDocInOrder tr:first td', form).each(function (i) {
          var w = $(this).width();
          $('#_TableDocInOrder tr:first th').eq(i).css('width', w + 'px');
      });
      recalcOrderTables(form);
  }

  function recalcOrderTables(form) {
      var v = $('#TableDoctors', form).is(':visible');
      var h1 = parseInt(form.css('height'));
      var h2 = parseInt(form.parent().css('height'));
      var diff = h2 - h1 - 10;
      if (v) {
          diff = Math.round(diff / 2);
      }
      var h1 = $('#TableDoctors', form).parent().height();
      var h2 = $('#TableDocInOrder', form).parent().height();
      $('#TableDoctors', form).parent().height(h1 + diff);
      $('#TableDocInOrder', form).parent().height(h2 + diff);
  }

function link(Url) {
    document.location.href = Url;
}
function work(data, div, url) {
    //alert(data);
    //var div = $('#dialog' + dialLev);
    div.append(data);
    var divId = div.attr('id');
    //alert("div: "+div.html());
    init(div);
    var w = parseInt($(div).css('width'));
    var h = parseInt($(div).css('height'));

    var wh = parseInt($(window).height());

    if (h > wh -100) {
        h = wh - 200;
    }

    var form = $('form[name!=aspnetForm]', $(div));
    updateOrder(form);
    var action = form.attr('action');
    console.debug(url + " = " + action);
    if (url != action) {
        link(action);
    } else {
        form.ajaxForm(function () {
            $('div[aria-labelledby=ui-dialog-title-' + divId + ']')
                    .find('a.ui-dialog-titlebar-close').click();
        });

        var buttons = [];
        if (form.find('input[type=submit][id$=btnSave]').length > 0) {
            buttons.push({ text: "Сохранить",
                click: function () {
                    $('input[type=submit][id$=btnSave]', this).click();
                }
            });
        }
        if (form.find('input[type=submit][id$=btnCancel]').length > 0) {
            buttons.push({ text: "Отмена", click: function () { $(this).dialog("close"); } });
        }
        if (form.find('input[type=submit][id$=btnSelectRMR]').length > 0) {
            buttons.push({ text: "Выбрать",
                click: function () {
                    if ($('#tlbRMRDoctor tr.row-highlight').length > 0) {
                        $('input[type=submit][id$=btnSelectRMR]', this).click();
                    } else {
                        return false;
                    }
                }
            });
        }
        if (form.find('input[type=submit][id$=btnSelect]').length > 0) {
            buttons.push({ text: "Выбрать", click: function () {
                var tr = $('#listInstitution tr.select');
                var id = tr.attr('id');
                if (id) {
                    var level = parseInt(divId.replace('dialog', ''));
                    $('#hfSelectLpu').val(id);
                    if (level == 0) {
                        $('#' + divId).addClass('notclose');
                    }
                    $(this).dialog("close");
                    if (level == 0) {
                        $('#_TableDoctors #_filterText5').val(tr.find('td.item').text()).keyup();
                    }
                }
            }
            });
        }

    if (form.find('input[type=submit][id$=btnSelectRMMDoc]').length > 0) {
        buttons.push({ text: "Выбрать", click: function () {

            var tr = $('#TableMedRegDoctors tr.select');
            var id = tr.attr('id');
            if (id) {
                var level = parseInt(divId.replace('dialog', ''));
                $('#hfRMRDocId').val(id);
            
                if (level == 0) {
                    $('#' + divId).addClass('notclose');
                }
                $(this).dialog("close");
                if (level == 0) {
                    $('#_TableDoctors #_filterText4').val(tr.find('td.item').text()).keyup();
                }
            }
        }
        });
    }

    div.dialog({ modal: true,
        height: h + 100,
        width: w + 50,
        buttons: buttons,
        open: function () {
            $('#sd_overlay').remove();
            var form = $('form', div);
            if ($('#OrderEditPanel').length > 0) {
                resizeOrderTables(form);
            }
        },
        close: function () {
            overlay();
            var notclose = $('#' + divId).hasClass('notclose');
            var level = parseInt(divId.replace('dialog', ''));
            console.debug(divId + ": " + level);
            $('div[aria-labelledby=ui-dialog-title-' + divId + ']').remove();
            if (!notclose) {
                if (level > 0) {
                    level--;
                    var sbmt = $('#dialog' + level + ' form');
                    sbmt.find('option[value="null"]:not(.static)').remove();
                    var url = sbmt.attr('action');
                    console.debug('reload dialog' + level + ' by ' + url);
                    var upd = $('#dialog' + level);
                    var options = {
                        target: upd,
                        url: url,
                        success: function () {
                            init(upd);
                            $('#sd_overlay').remove();
                            upd.find('form').ajaxForm(function () {
                                $('div[aria-labelledby=ui-dialog-title-dialog' + level + ']')
                                            .find('a.ui-dialog-titlebar-close').click();
                            });
                        }
                    };
                    sbmt.ajaxSubmit(options);
                    //upd.load(url, function () { init(upd) });
                } else {
                    $('form[name=aspnetForm] select:not(.nullable) option[value="null"]:not(.static)').remove();
                    $('form[name=aspnetForm]').submit();
                }
            } else {
                $('#sd_overlay').remove();
            }
            div.empty();
        }
    });
        //                    $('#btUpdate').click();
    }    
}
function init(obj) {    
    $('form input[type=submit][id$=btnSave]', obj).hide();
    $('form input[type=submit][id$=btnCancel]', obj).hide();
    $('form input[type=submit][id$=btnSelect]', obj).hide();
    $('form input[type=submit][id$=btnSelectRMR]', obj).hide();
    $('a.delete.entity:not(.done)', obj).addClass('done').click(function () {
        if (confirm("Вы уверены, что хотите удалить элемент?")) {
            var url = $(this).attr('href');
            overlay();
            $.ajax({
                url: url,
                success: function (data) { $('form').submit(); }
            });
        }
        return false;
    });
    $('a.modal:not(.done)', obj).addClass('done').click(function () {
        if ($(this).hasClass('disabled')) {
            return false;
        }
        overlay();
        var url = $(this).attr('href');
        var dialLev = $('.ui-dialog[aria-labelledby!=ui-dialog-title-treeLpu]').length;
        if (!dialLev) {
            dialLev = 0;
        }
        var div = $('#dialog' + dialLev);
        $.ajax({
            url: url,
            success: function (data) { work(data, div, url); }
        });
        //div.load(url, 


        //).addClass('done');
        return false;
    });
    $("table", obj).each(function () {
        var th = $('tbody>tr:first>th:first', $(this));
        var tr = th.parent();
        var body = tr.parent();
        var head = $("<thead></thead>");
        head.append(tr);
        body.before(head);
        //head.append(tr);
        //$(this).removeClass("filtered");
    });
    $('input.date:not(.hasDatepicker)', obj).attachDatepicker();
    $('table.filtered:not(.doneFilter)', obj).columnFilters({ excludeColumns: [0], alternateRowClassNames: ['odd', 'even'] });
    $('table.filtered2:not(.doneFilter)', obj).columnFilters({ excludeColumns: [0, 1], alternateRowClassNames: ['odd', 'even'] });
    $('table.filtered3:not(.doneFilter)', obj).columnFilters({ excludeColumns: [0, 1, 2], alternateRowClassNames: ['odd', 'even'] });
    $('table.scrollable:not(.doneScroll)', obj).scrollbarTable(parseInt($(window).height() - 215 - $('div#messages').height()));
    $('table.scrollable-100:not(.doneScroll)', obj).scrollbarTable({ height: 100 });
    $('table.scrollable-200:not(.doneScroll)', obj).scrollbarTable({ height: 200 });

    $('table#tblValues .template-value', obj).keyup(function () {
        var id = $(this).attr('id');
        var val = $(this).val().replace(';', '').replace('^', '');
        var value = $('#hfValues', obj).val();
        console.debug(value);
        value = value.replace(new RegExp(';' + id + '~[^;]*'), ';' + id + '~' + val);
        console.debug(value);
        $('#hfValues').val(value);
    });

    $('#dialog-print fieldset#form', obj).wrap('<form />');
    initPrintButtons(obj);
    initPrint(obj);
    initInstitutionTree(obj);
    initCheckSpecExtGroup(obj);
    initComboSpecNew(obj);
    initCombos(obj);
    initDeleted(obj);
    $('#comboYear', obj).change(function () {
        $(this).closest('form').submit();
    });
    initRMR(obj);
    initRMRDoctorSearch(obj);

    //TEST
}

function initDeleted(obj) {
    $('select', obj).each(function () {
        $('option[type]:first', this).each(function () {
            var type = $(this).attr('type');
            $.ajax({
                url: 'deleted?class=' + type,
                success: function (data) {
                    if (data) {
                        var ids = data.split(',');
                        for (var i in ids) {
                            var opt = $('option[type=' + type + '][value=' + ids[i] + ']');
                            if (opt.attr('selected')) {
                                opt.attr('disabled', 'disabled');
                            } else {
                                opt.remove();
                            }
                            //$('option[type=' + type + '][value=' + ids[i] + ']').attr('disabled', 'disabled');
                        }
                    }
                }
            });
        });
    });
}

function initCombos(obj) {
    var act = $('form:first', obj).attr('action');
    var postback = $('form:first', obj).attr('postback') == 'True';
    var setNull = (act.indexOf('id=0') >0 || act.indexOf('id=') < 0)&&!postback;
    $('select:not(.nullable)', obj).each(function () {
        var v = $(this).val();
        if ($(this).find('option[value="null"]').length == 0) {
            $(this).prepend('<option value="null">- не выбрано -</option>');
            if (setNull) {
                $(this).val('null');
            }
        }
    });
}

function initCheckSpecExtGroup(obj) {
    checkSpecAndGroup(obj);
    $('#comboExpGroup', obj).change(function () {
        checkSpecAndGroup(obj);
    });
    $('#comboSpecNew', obj).change(function () {
        checkSpecAndGroup(obj);
    });
}

function checkSpecAndGroup(obj) {
    var l = $('#comboExpGroup', obj).length;
    if (l == 0) {
        return true;
    }
    var v = $('#comboExpGroup option:selected', obj).val();
    if (v == '0' || v == 'null') {
        $('#comboExpGroup').css('border', '1px solid blue');
        $('#comboSpecNew').css('border', '1px solid blue');
        return true;
    }
    var specs = $('#comboExpGroup option:selected', obj).attr('specialities');
    //alert(specs);
    var id = $('#comboSpecNew option:selected', obj).val();
    if (specs) {
        if (specs.indexOf(';' + id + ';') >= 0) {
            $('#comboExpGroup').css('border', '1px solid blue');
            $('#comboSpecNew').css('border', '1px solid blue');
            return true;
        } else {
            $('#comboExpGroup').css('border', '1px solid red');
            $('#comboSpecNew').css('border', '1px solid red');
            return false;
        }
    }
}

function initComboSpecNew(obj) {
    $('span#specDate', obj).text($('select#comboSpecNew option:selected', obj).attr('date'));
    $('select#comboSpecNew:not(.done)', obj).addClass('done').change(function () {
        $('span#specDate', obj).text($('option:selected', this).attr('date'));
    });
}

function initInstitutionTree(obj) {
    var id = $('#comboInstitution option:selected', obj).val();
    var href = $('a#openLpuTree', obj).attr('href');
    var rmrhref = $('a#openRMRDoctorSearch', obj).attr('href');
    $('a#openLpuTree', obj).attr('href', href + '?id=' + id);
    $('a#openRMRDoctorSearch', obj).attr('href', rmrhref + '?id=' + id);
    $('#comboInstitution', obj).change(function () {
        var href = $('a#openLpuTree', obj).attr('href');
        var rmrhref = $('a#openRMRDoctorSearch', obj).attr('href');
        //alert($('option:selected', this).val());
        href = href.replace(/id=.*/, 'id=' + $('option:selected', this).val());
        rmrhref = rmrhref.replace(/id=[^&]*/, 'id=' + $('option:selected', this).val());
        $('a#openLpuTree', obj).attr('href', href);
        $('a#openRMRDoctorSearch', obj).attr('href', rmrhref);
    });

    var locUrl = $('a#addLocality').attr('href');
    locUrl += '?region=' + $('#hfRegions', obj).val();
    $('a#addLocality').attr('href', locUrl);
    var instUrl = $('a#addInstitution').attr('href');
    instUrl += '?locality=' + $('#hfLocalities', obj).val();
    $('a#addInstitution').attr('href', instUrl);

    $('#listLocality tr', obj).hide();
    $('#listInstitution tr', obj).hide();
    $('#listRegion td.item', obj).click(function () {
        var region = $(this).parent().attr('id');
        $('#listLocality tr[region!=' + region + ']', obj).hide().removeClass('select');
        $('#listInstitution tr', obj).hide().removeClass('select');
        $('#listLocality tr[region=' + region + ']', obj).show();
        $('#listRegion tr', obj).removeClass('select');
        $(this).parent().addClass('select');
        $('#hfRegions', obj).val(region);
        var locUrl = $('a#addLocality').attr('href');
        locUrl = locUrl.replace(/region=.*/, 'region=' + region);
        $('a#addLocality').attr('href', locUrl);
    });
    $('#listLocality td.item', obj).click(function () {
        var locality = $(this).parent().attr('id');
        $('#listInstitution tr[locality!=' + locality + ']', obj).hide().removeClass('select');
        $('#listInstitution tr[locality=' + locality + ']', obj).show();
        $('#listLocality tr').removeClass('select');
        $(this).parent().addClass('select');
        $('#hfLocalities', obj).val(locality);
        var instUrl = $('a#addInstitution').attr('href');
        instUrl = instUrl.replace(/locality=.*/, 'locality=' + locality);
        $('a#addInstitution').attr('href', instUrl);
    });
    $('#listInstitution td.item', obj).click(function () {
        $('#listInstitution tr', obj).removeClass('select');
        $(this).parent().addClass('select');
        $('#hfInstitutions', obj).val($(this).parent().attr('id'));
    });

    $('#listRegion tr[id=' + $('#hfRegions', obj).val() + ']', obj).addClass('select');
    $('#listLocality tr[id=' + $('#hfLocalities', obj).val() + ']', obj).addClass('select');
    $('#listInstitution tr[id=' + $('#hfInstitutions', obj).val() + ']', obj).addClass('select');

    $('#listRegion tr.select td.item', obj).click();
    $('#listLocality tr.select td.item', obj).click();

    $('#listRegion', obj).parent().scrollTop($('#hfScrollRegion', obj).val());
    $('#listLocality', obj).parent().scrollTop($('#hfScrollLocality', obj).val());
    $('#listInstitution', obj).parent().scrollTop($('#hfScrollInstitution', obj).val());

    
    $('#listRegion', obj).parent().scroll(function () {
        $('#hfScrollRegion', obj).val($(this).scrollTop());
    });
    $('#listLocality', obj).parent().scroll(function () {
        $('#hfScrollLocality', obj).val($(this).scrollTop());
    });
    $('#listInstitution', obj).parent().scroll(function () {
        $('#hfScrollInstitution', obj).val($(this).scrollTop());
    });
}

function initRMRDoctorSearch(obj) 
{
    var tr = $('#tlbRMRDoctor', obj).find('tr');
    tr.bind('click', function (event) {
        var id = $(this).attr('id');
        tr.removeClass('row-highlight');
        $(this).addClass('row-highlight').find('td');
        $('#hfRMRDcotorId', obj).val(id);

    });
}

function initFilter(obj) {
    $('#btnOutOfOrder', obj).click(function () {
//        if ($('#_TableDoctors input#_filterText6').val() != '') {
//            $('#_TableDoctors input#_filterText6').val('').keyup();
//            return false;
//        }
        $('#_TableDoctors input#_filterText6').val('нет').keyup();
        return false;
    });
    $('#btnInOrder', obj).click(function () {
//        if ($('#_TableDoctors input#_filterText6').val() != '') {
//            $('#_TableDoctors input#_filterText6').val('').keyup();
//            return false;
//        }
        $('#_TableDoctors input#_filterText6').val('*да').keyup();
        return false;
    });
    $('#btnAll', obj).click(function () {
        $('#_TableDoctors input#_filterText6').val('').keyup();
        return false;
    });
    filterBySpec(obj, $('#comboSpecFilter', obj));
    $('#comboSpecFilter', obj).change(function () {
        filterBySpec(obj, this);
    });
}

function filterBySpec(obj, combo) {
    var specId = $('option:selected', combo).val();
    $('#TableDoctors tr td._filterCol0', obj).removeClass('_hide');
    if (specId != 'null') {
        $('#TableDoctors tr[speciality!=' + specId + '] td._filterCol0', obj).addClass('_hide');
    }
    $('#_TableDoctors input._filterText:first').keyup();
}

function initPrintButtons(obj) {
    $('div.print', obj).click(function () {
        var pos = $(this).offset();
        var popup = $('<div class="popup" />');
        var div = $('<div class="popup-content" style="padding: 10px" />');
        var content = $(this).contents().clone();
        //popup.append('<div class="print" />');
        div.append(content);
        popup.append(div);
        popup.css('top', pos.top)
             .css('left', pos.left);
        popup.mouseleave(function () { popup.remove(); });
        $('body').append(popup);
        initPrint(popup);
    });
}

function processRmr() {
    var select = $('select#comboInstitution');
    var t = select.val();
    $('#hfInstitution').val(t);
    var rmr = $('option:selected', select).attr('rmr');
    //alert(rmr);
    if (!rmr || rmr == '00000000-0000-0000-0000-000000000000') {
        $('a#openRMRDoctorSearch').addClass('disabled');
    } else {
        $('a#openRMRDoctorSearch').removeClass('disabled');
    }
}

function initRMR(obj) {
    processRmr();
    var href = $('a#openRMRDoctorSearch', obj).attr('href');
    var surname = $('input#tfSurname', obj).val();
    if (!surname || surname.trim() == '') {
        surname = 'А';
    }
    $('a#openRMRDoctorSearch', obj).attr('href', href + "&surname=" + surname);
    $('input#tfSurname:not(.done)', obj).keyup(function () {
        var href = $('a#openRMRDoctorSearch', obj).attr('href');
        var surname = $(this).val();
        if (!surname || surname.trim() == '') {
            surname = 'A';
        }
        href = href.replace(/surname=.*/, 'surname=' + surname.replace(' ', '_'));
        $('a#openRMRDoctorSearch', obj).attr('href', href);
    });
    $('select#comboInstitution:not(.done)', obj).addClass('done').change(function () {
        processRmr();
    });
    $('#b_RMRSearch:not(.done)', obj).addClass('done').click(function () {
        var form = $(this).closest('form');
        var surname = $('#tbRMRSearch', form).val();
        var action = form.attr('action');
        surname = surname.replace(' ', '_');
        action = action.replace(/surname=.*/, 'surname=' + surname);
        $.ajax({
            url: action,
            success: function (data) {
                var tab = $('#tlbRMRDoctor', data);
                $('tr:first', tab).remove();
                $('#tlbRMRDoctor', form).replaceWith(tab);
                initRMRDoctorSearch(form);
                $('#tlbRMRDoctor tr:first td', form).each(function (i) {
                    //alert(i + ': ' + $(this).width());
                    $('#_tlbRMRDoctor tr:first th', form).eq(i).css('width', $(this).width() + 'px')
                });
            }
        });
        return false;
    });
}

function initPrint(obj) {
    $('a.print', obj).attr('target', '_blank').addClass('done');
//    .click(function () {
//        //var link = $(this);
//        var url = $(this).attr('href');
//        $("#dialog-print").dialog({
//            height: 200,
//            width: 350,
//            modal: true,
//            closeOnEscape: false,
//            buttons: {
//                "Печать": function () {
//                    var date = '' + $('#report-date').val();
//                    var number = '' + $('#report-number').val();
//                    url += '&date=' + date + '&number=' + number;
//                    link(url);
//                    $(this).dialog("close");
//                    //$('<a href="google.ru" target="_blank" />').appendTo('body').click();
//                },
//                "Отмена": function () {
//                    $(this).dialog("close");
//                }
//            },
//            close: function () {
//            }
//        });
//        return false;
//    });
}

function updateOrder(form) {
    var a = form.find('a#editOrder');
    if (a.length > 0) {
        if (a.hasClass('active')) {
            form.find('#_TableDoctors').show().next().show();
            form.find('#TableDoctors').parent().show().next().show();
            form.find('#TableDocInOrder').next().css({ height: '200px' });
            form.find('a.up').show();
            form.find('input[type!=submit],select').removeAttr("disabled");
            $('#TableDoctors tr:first td', form).each(function (i) {
                var w = $(this).width();
                $('#_TableDoctors tr:first th').eq(i).css('width', w+'px');
            });
            $('#TableDocInOrder tr:first td', form).each(function (i) {
                var w = $(this).width();
                $('#_TableDocInOrder tr:first th').eq(i).css('width', w + 'px');
            });
        } else {
            form.find('#_TableDoctors').hide().next().hide();
            form.find('#TableDoctors').parent().hide().next().hide();
            form.find('#TableDocInOrder').next().css({ height: '400px' });
            form.find('a.up').hide();
            form.find('input[type!=submit]:not([fidx]),select').attr("disabled", "disabled");
        }
    }
    recalcOrderTables(form);
}

function qualifyURL(url) {
    var a = document.createElement('a');
    a.href = "";
    console.debug(a.href);
}